﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ServiceCore.Tool.Quartz
{

    #region  处理定时队列
    public class AddWorkPlaan
    {
        public IJobDetail job { get; set; }

        public ITrigger trigger { get; set; }
    }
    public class QuartzOption
    {
        List<AddWorkPlaan> workplan = new List<AddWorkPlaan>();
        public QuartzOption AddOption<T>(string Name, string Group, int Seconds) where T : IJob
        {
            workplan.Add(new AddWorkPlaan()
            {
                job = JobBuilder.Create<T>().WithIdentity(Name, Group).Build(),
                trigger = TriggerBuilder.Create().WithIdentity(Name, Group).WithSimpleSchedule(a => a.WithIntervalInSeconds(Seconds).RepeatForever()).Build()
            });
            return this;
        }

        public QuartzOption AddOption<T>(string Name, string Group, string setDateTime) where T : IJob
        {
            workplan.Add(new AddWorkPlaan()
            {
                job = JobBuilder.Create<T>().WithIdentity(Name, Group).Build(),
                trigger = TriggerBuilder.Create().WithIdentity(Name, Group).
                WithCronSchedule(setDateTime).Build()
            });
            return this;
        }
        public List<AddWorkPlaan> Build()
        {
            return workplan;
        }
    } 
    public class IOCJobFactory : IJobFactory
    {
        private readonly IServiceProvider _serviceProvider;

        public IOCJobFactory(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }
        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            return _serviceProvider.GetService(bundle.JobDetail.JobType) as IJob;
        }

        public void ReturnJob(IJob job)
        {
            var disposable = job as IDisposable;
            disposable?.Dispose();
        }
    }

    public class QuartzStartup
    {
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly IJobFactory _iocJobfactory;
        private IScheduler _scheduler;
        public QuartzStartup(IJobFactory iocJobfactory, ILogger<QuartzStartup> logger, ISchedulerFactory schedulerFactory)
        {
            //1、声明一个调度工厂
            this._schedulerFactory = schedulerFactory;
            this._iocJobfactory = iocJobfactory;
        }
        public async Task<string> Start()
        {
            var workplan = new QuartzOption()
               .AddOption<check_aliface>("check_aliface", "AliFace", "0 30 * * * ? *")
               .Build();

            _scheduler = await _schedulerFactory.GetScheduler();
            _scheduler.JobFactory = this._iocJobfactory;
            await _scheduler.Start();
            foreach (var item in workplan)
            {
                await _scheduler.ScheduleJob(item.job, item.trigger);
            }
            return await Task.FromResult("将触发器和任务器绑定到调度器中完成");
        }
        public void Stop()
        {
            if (_scheduler == null)
            {
                return;
            }

            if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
            {
                _scheduler = null;
            }
            else
            {

            }
        }
    }
    #endregion
}
 
